package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.loan

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonLoanConfirmBinding
import org.json.JSONObject

class LoanConfirmCameroonActivity : AppCompatActivity() {

    private lateinit var loanViewModel: LoanCameroonViewModel
    private lateinit var binding: ActivityCameroonLoanConfirmBinding
    private lateinit var adapter: LoanConfirmCameroonPageAdapter

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        loanViewModel = ViewModelProvider(this)[LoanCameroonViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonLoanConfirmBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val dueAmount = binding.dueAmount
        val list = binding.list
        val submit = binding.submit

        // 初始化adapter
        adapter = LoanConfirmCameroonPageAdapter(emptyList())
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 贷款金额
        val sliderAmount = intent.getStringExtra("amount") ?: ""
        loanViewModel.sliderAmount = sliderAmount
        if (sliderAmount.isBlank()) {
            finish()
            return
        }

        // 页面loading状态接口监听
        loanViewModel.loadingResult.observe(this@LoanConfirmCameroonActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        loanViewModel.pageDetailResult.observe(this@LoanConfirmCameroonActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                // TODO: 失败
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.success != null) {
                // TODO: 成功
                dueAmount.text = pageDetailResult.success.optString("amount")

                val days = pageDetailResult.success.optString("daysFormat")
                updateDaysSpanText(days)
            }
            if (pageDetailResult.list != null) {
                adapter.dataList = pageDetailResult.list
                adapter.notifyDataSetChanged()
            }
        })

        // 提交申请接口监听
        loanViewModel.createLoanResult.observe(this@LoanConfirmCameroonActivity, Observer {
            val createLoanResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (createLoanResult.error != null) {
                showMessage(createLoanResult.error)
            }
            if (createLoanResult.success != null) {
                loanViewModel.mainProcess()
            }
        })

        // 流程接口监听
        loanViewModel.mainProcessResult.observe(this@LoanConfirmCameroonActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                loanViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        loanViewModel.nextRouterResult.observe(this@LoanConfirmCameroonActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击申请
        back.setOnClickListener {
            finish()
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 点击提交
        submit.setOnClickListener {
            loading.visibility = View.VISIBLE
            loanViewModel.createLoan()
            hitPointCameroon("LOAN_APPLY_COMMIT")
        }

        // 查询页面详情
        loading.visibility = View.VISIBLE
        loanViewModel.pageDetail()
    }

    private fun updateDaysSpanText(days: String) {
//        val text = "≤${days}(days)"
//        val words = "(days)"
//        val gStart = text.indexOf(words)
//        if (gStart >= 0) {
//            val gEnd = gStart + words.length
//            val spanString = SpannableString(text)
//            spanString.setSpan(
//                RelativeSizeSpan(0.6F),
//                gStart,
//                gEnd,
//                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
//            )
//            spanString.setSpan(
//                ForegroundColorSpan(Color.parseColor("#80000000")),
//                gStart,
//                gEnd,
//                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
//            )
//
//            binding.dueDate.text = spanString
//        }
        binding.dueDate.text = days
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    fun startNextActivity(
        activity: Class<out AppCompatActivity>? = null,
        params: HashMap<String, String> = HashMap()
    ) {
        val nextActivity = activity ?: return
        try {
            val intent = Intent(this, nextActivity)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            params.keys.forEach { gKey ->
                intent.putExtra(gKey, params[gKey])
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}


class LoanConfirmCameroonPageAdapter(
    var dataList: List<JSONObject>
) :
    RecyclerView.Adapter<LoanConfirmCameroonPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_cameroon_loan_confirm_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val title: TextView = view.findViewById(R.id.title)
        private val detail: TextView = view.findViewById(R.id.detail)
        private val titleHeader: View = view.findViewById(R.id.titleHeader)
        private val line: View = view.findViewById(R.id.line)

        fun bindData(item: JSONObject, position: Int) {
            title.text = item.optString("showName")
            detail.text = item.optString("showDetail")

            val isBold = item.optString("title")
            if (isBold.contains("YES", true)) {
                line.visibility = View.VISIBLE
                if (position == 0) {
                    titleHeader.visibility = View.GONE
                } else {
                    titleHeader.visibility = View.VISIBLE
                }
                title.setTextColor(Color.parseColor("#222222"))
                title.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                detail.typeface = Typeface.defaultFromStyle(Typeface.BOLD)

            } else {
                title.setTextColor(Color.parseColor("#999999"))
                title.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                detail.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                line.visibility = View.GONE
                titleHeader.visibility = View.GONE
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data, position)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}